package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * 订单
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 移动端分页查询订单
     */
    @GetMapping("/userPage")
    public R<Page> userPage(int page, int pageSize) {
        //分页构造器
        Page<Orders> ordersPage = new Page<>(page, pageSize);

        //条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        //添加条件
        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        queryWrapper.orderByDesc(Orders::getOrderTime);

        //执行查询
        Page<Orders> ordersPages = orderService.page(ordersPage, queryWrapper);
        return R.success(ordersPages);
    }

    /**
     * 后台分页查询订单
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, Long number, LocalDateTime begin,LocalDateTime end) {
        //分页构造器
        Page<Orders> orderPage = new Page<>(page, pageSize);

        //条件构造
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        //添加条件
        queryWrapper.like(number!=null,Orders::getId,number);
        queryWrapper.between(begin!=null && end!=null,Orders::getOrderTime,begin,end);

        //执行查询
        Page<Orders> orderPages = orderService.page(orderPage, queryWrapper);
        return R.success(orderPages);
    }

    /**
     * 后台修改订单状态
     */
    @PutMapping()
    public R<String> update(@RequestBody Orders orders) {
         //获取当前订单id
        Long ordersId = orders.getId();

        //接受要改变的状态
        Integer status = orders.getStatus();

        //条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        //添加条件
        queryWrapper.eq(Orders::getId,ordersId);

        //执行
        Orders one = orderService.getOne(queryWrapper);

        //修改该订单的状态
        one.setStatus(status);

        orderService.updateById(one);

        return R.success("订单状态修改成功");
    }


}
